#!/usr/bin/env python
# -*- coding: utf-8 -*-

# forever mako
import datetime,time

OneSecond=datetime.timedelta(seconds=1)

class EventTimeData:
    def __init__(self,TimeInterval,LastExcuteTime):
        self.TimeInterval=TimeInterval
        self.LastExcuteTime=LastExcuteTime

class MainLoop:
    def __init__(self,Fps=30):
        self.Fps=Fps
        self.LastTime=datetime.datetime.now()
        self.Running=False
        self.TimeEvent={}
        self.LoopInterval=OneSecond/self.Fps
        
    def RegisterTimeEvent(self,TimeInterval,EventFunction):
        self.TimeEvent[EventFunction]=EventTimeData(TimeInterval,datetime.datetime.now())
        
    def Run(self):
        NowTime=datetime.datetime.now()
        for F in self.TimeEvent:
            if (NowTime-self.TimeEvent[F].LastExcuteTime).total_seconds()>=self.TimeEvent[F].TimeInterval:
                F()
                self.TimeEvent[F].LastExcuteTime=NowTime
            
        
    def BeginLoop(self):
        self.Running=True
        while self.Running:
            DeltaTime=datetime.datetime.now()-self.LastTime
            if DeltaTime>=self.LoopInterval:
                self.LastTime=datetime.datetime.now()
                self.Run()
            else:
                time.sleep((self.LoopInterval-DeltaTime).total_seconds())
    
    
    def EndLoop(self):
        self.Running=False
        
            
        
    
    